package net.swa.system.web.action;

import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Required;
import net.swa.system.beans.entity.Menu;
import net.swa.system.beans.entity.Role;
import net.swa.system.service.ICommonService;
import net.swa.system.util.annotation.Log;

public class RoleAction extends AbstractBaseAction
{

	private static final long serialVersionUID = 6771957130989908200L;

	private ICommonService commonService;

	private Role role;

	@Log(description = "查看角色列表")
	public String listPage() throws Exception
	{
		return "list";
	}

	@Log(description = "查看角色树")
	public String rootTree() throws Exception
	{
		// User user = getCurrentUser();
		String[] attrNames = new String[1];
		Object[] attrValues = new Object[1];
		StringBuilder buffer = new StringBuilder();
		buffer.append("<item text='root' id='0' open='1'  im0='user.png' im1='user.png' im2='user.png'  >");
		List<Role> roles = commonService.search(Role.class, attrNames, attrValues);
		for (Role role : roles)
		{
			buffer.append(role.toXml());
		}
		buffer.append("</item>");

		outString(buffer.toString());
		return null;
	}

	@Log(description = "编辑角色")
	public String edit() throws Exception
	{
		if (role == null)
		{
			role = new Role();
		} else
		{
			role = commonService.commonFind(Role.class, role.getId());
		}
		return "edit";
	}
	

	@Log(description = "保存角色")
	public String save() throws Exception
	{
		String[] menuIds = getRequest().getParameterValues("menuId");
		List<Menu> menus = new ArrayList<Menu>();
		if (menuIds != null)
		{
			for (String s : menuIds)
			{
				Menu menu = commonService.commonFind(Menu.class, Long.parseLong(s));
				menus.add(menu);
			}
		}
		role.setMenus(menus);
		if (role.getId() == 0)
		{
			commonService.commonAdd(role);
		} else
		{
			commonService.commonUpdate(role);
		}
		outSuccess();
		return null;
	}

	public ICommonService getCommonService()
	{
		return commonService;
	}

	@Required
	@Resource
	public void setCommonService(ICommonService commonService)
	{
		this.commonService = commonService;
	}

	public Role getRole()
	{
		return role;
	}

	public void setRole(Role role)
	{
		this.role = role;
	}

}
